import { Injectable } from '@nestjs/common';
import { CreateGroupDto } from './dto/create-group.dto';
import { UpdateGroupDto } from './dto/update-group.dto';
import { In, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Group } from './entities/group.entity';
import logger from 'src/common/utils/log';
import { GroupStatusEnum, MatchStatusEnum } from 'src/common/constant/enums';

@Injectable()
export class GroupService {
  constructor(
    @InjectRepository(Group)
    private repository: Repository<Group>
  ) {}
  async create(createGroupDto: CreateGroupDto) {
    return await this.repository.save(createGroupDto);
  }

  async saveList(groups: Partial<Group>[]) {
    const entities = groups.map((v) => {
      return this.repository.create(v);
    });
    return await this.repository.save(entities);
  }

  async findOne(id: number) {
    return await this.repository.findOne({ where: { id } });
  }

  async update(id: number, updateGroupDto: UpdateGroupDto) {
    return await this.repository.update(id, updateGroupDto);
  }
  async remove(id: number) {
    return await this.repository.delete([id]);
  }

  async removeIds(ids: number[]) {
    return await this.repository.delete(ids);
  }
  async removeInStageIds(stageIds: number[]) {
    const groups = await this.repository.find({
      where: {
        stage: {
          id: In(stageIds),
        },
      },
    });
    return await this.repository.remove(groups);
  }
  async listByStageId(stageId: number) {
    return await this.repository.find({
      where: { stageId },
    });
  }
  async listByStageIdWithScores(stageId: number) {
    return await this.repository.find({
      where: { stageId },
      relations: ['groupPlayerScores'],
    });
  }
  async getByIdWithMatches(id: number) {
    return await this.repository.findOne({
      where: { id },
      relations: ['matchInfos'],
    });
  }
  async checkFinish(id: number) {
    logger.info('finishGroup...', id);
    const { matchInfos } = await this.getByIdWithMatches(id);
    const isAllFinished = matchInfos.every(
      (match) => match.status === MatchStatusEnum.Finished,
    );
    if (isAllFinished) {
      await this.update(id, {
        status: GroupStatusEnum.Finished,
      });
    }
    logger.info('finishGroup...', isAllFinished);
    return isAllFinished;
  }
}
